#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@author: xiaodun
@date: 2025/9/1820:25
"""
import os

from selenium import webdriver
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.edge.options import Options as EdgeOptions
from dl_auto_test.config.config import config
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.service import Service






class DriverManager:

    @staticmethod
    def create_driver():
        browser_name=config.get_browser_name().lower()

        headless=config.is_headless()

        if browser_name=="chrome":
            options=ChromeOptions()
            if headless:
                options.add_argument("--headless")
            options.add_argument("--no-sandbox")
            options.add_argument("--disable-dev-shm-usage")
            options.add_argument("--window-size=1920,1080")
            options.add_argument("--disable-infobars")
            options.add_argument('--disable-extensions')
            options.add_argument('--disable-images')
            options.add_experimental_option('detach', True)#浏览器不自动关闭
            options.page_load_strategy='eager'
            options.add_argument("--disable-save-password-bubble")
            options.add_experimental_option("prefs", {
                "credentials_enable_service": False,
                "profile.password_manager_enabled": False
            })
            # os.environ['SE_DRIVER_MIRROR_URL']='https://npm.taobao.org/mirrors/chromedrive'
            # os.environ['SE_DRIVER_MIRROR_URL']='https: // registry.npmmirror.com / binary.html?path = chrome -for -testing /'
            driver=webdriver.Chrome(options=options,service=Service(r'../dl_auto_test/chromedriver.exe'))
        elif browser_name=="firefox":
            options=FirefoxOptions()
            if headless:
                options.add_argument("--headless")
            driver=webdriver.Firefox(options=options)
        elif browser_name=="edge":
            options=EdgeOptions()
            if headless:
                options.add_argument("--headless")
            driver=webdriver.Edge(options=options)
        else:
            raise ValueError(f"不支持的浏览器类型：{browser_name}")

        driver.implicitly_wait(config.get_implicit_wait())#隐式等待
        driver.maximize_window()
        return driver